﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace WinShare
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (WinShare.Properties.Settings.Default.FirstRun == true)
            {
                //MessageBox.Show("First Time Run!");
                if (MessageBox.Show("This is the first time run, Would you like to set an auto-update directory?", "WinShare First Time Run", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    FolderBrowserDialog updateFolder = new FolderBrowserDialog();
                    if (updateFolder.ShowDialog() == DialogResult.OK)
                    {
                        WinShare.Properties.Settings.Default.Update_Location = updateFolder.SelectedPath;
                        WinShare.Properties.Settings.Default.Save();
                        //MessageBox.Show(updateFolder.SelectedPath);
                    }
                }
                else
                {
                    WinShare.Properties.Settings.Default.Updates_Enabled = false;
                }
                WinShare.Properties.Settings.Default.FirstRun = false;
            }

            if (WinShare.Properties.Settings.Default.Update_Location != null)
            {
                if (checkUpdates(WinShare.Properties.Settings.Default.Update_Location) == false)
                {
                    string[] args = Environment.GetCommandLineArgs();

                    if (args.Length >= 2 && args[1] == "/shareasite")
                    {
                        WindowsMessageAPI.MessageHandler msgService;
                        msgService = new WindowsMessageAPI.MessageHandler("WinShare-Client");
                        IntPtr ShareSite = msgService.RegisterMessage("ShareSite");
                        IntPtr server = msgService.GetHandle("WinShare-Server");
                        if (server.ToInt32() != 0)
                        {
                            msgService.SendMessage(server, ShareSite);
                            msgService.Dispose();
                            Application.Exit();
                        }
                        else
                        {
                            Application.Run(new Form1(true));
                        }
                    }
                    else
                    {
                        Application.Run(new Form1());
                    }
                }
                else
                {
                    Application.Exit();
                }
            }
        }

        public static bool checkUpdates(string updateLocation)
        {
            if (WinShare.Properties.Settings.Default.Updates_Enabled == true)
            {
                bool didUpdate = false;
                Debug.WriteLine("Update Location is: " + updateLocation);
                string updateSetup = updateLocation + Path.DirectorySeparatorChar + "setup.exe";
                Debug.WriteLine("Update setup is: " + updateSetup);
                if (File.Exists(updateSetup))
                {
                    Debug.WriteLine("File Found! Checking timestamp...");
                    Debug.WriteLine("Setup write time:" + File.GetLastWriteTime(updateSetup));
                    Debug.WriteLine("Last write time:" + WinShare.Properties.Settings.Default.Update_Date);
                    if (File.GetLastWriteTime(updateSetup).ToString() != WinShare.Properties.Settings.Default.Update_Date.ToString())
                    {
                        Debug.WriteLine("Appearently, their not equal.. Updating..");
                        try
                        {
                            Process updateProcess = new Process();
                            updateProcess.StartInfo.FileName = updateSetup;
                            updateProcess.Start();
                            WinShare.Properties.Settings.Default.Update_Date = File.GetLastWriteTime(updateSetup);
                            WinShare.Properties.Settings.Default.Save();
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                        didUpdate = true;
                    }
                }
                return didUpdate;
            }
            else
            {
                return false;
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = (Exception)e.ExceptionObject;

                MessageBox.Show("Whoops! Please contact the developers with the following"
                      + " information:\n\n" + ex.Message + ex.StackTrace,
                      "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                Application.Exit();
            }
        }
    }

 
}
